package com.solution.webutil;


import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.solution.constant.LoginConstants;
import com.solution.delegate.UserInfoServiceDelegate;
import com.solution.model.UserInfo;

public class LoginErrorServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private ServletContext context;

	public void init(ServletConfig config) throws ServletException {
		this.context   =  config.getServletContext();
    }
	public  void doGet(HttpServletRequest request, HttpServletResponse  response)
	throws IOException, ServletException {
		doPost( request,  response);
	}

	public  void doPost(HttpServletRequest request, HttpServletResponse  response)
    	throws IOException, ServletException {
		try{
			UserInfoServiceDelegate userInfoService= new UserInfoServiceDelegate();
			String userName = request.getParameter("j_username");
			if(userName == null){
				userName = request.getRemoteUser();
			}
			UserInfo userInfo = userInfoService.getUserDetail(userName);
			if(userInfo!=null){
				// for blocked user
				if(userInfo.getStatus()== LoginConstants.USER_BLOCKED){
					request.setAttribute("invalidMsg","User already appeared");
				}
				else if(userInfo.getStatus()== LoginConstants.USER_DEACTIVE){
					request.setAttribute("invalidMsg","User is blocked");
				}
				else if(userInfo.getStatus()== LoginConstants.USER_LOGIN_EXPIRED){
					request.setAttribute("invalidMsg","User is expired");
				}
				else{
					userInfo.setRetryPasswordCount((byte)(userInfo.getRetryPasswordCount()-1));
					if(userInfo.getRetryPasswordCount()<=0){
						userInfo.setStatus((short)LoginConstants.USER_DEACTIVE);
						request.setAttribute("invalidMsg","Your retry password limit finished.User is blocked");
					}
					else{
						request.setAttribute("invalidMsg","Invalid Password . "+userInfo.getRetryPasswordCount()+" attempts remaining");
					}
					userInfoService.update(userInfo);
				}
			}
			else{
				request.setAttribute("invalidMsg","Invalid user name");
			}
			context.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
		}
		catch(Exception ex){
			context.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
		}
	}
}